//
//  TouchView.m
//  PaletteDemo
//
//  Created by 卢浩 on 16/4/26.
//  Copyright © 2016年 卢浩. All rights reserved.
//

#import "TouchView.h"

@implementation TouchView

//懒加载
- (NSMutableArray *)allPoints{
    if (_allPoints == nil) {
        _allPoints = [[NSMutableArray alloc]init];
    }
    return _allPoints;
}

//懒加载
- (NSMutableArray *)points{
    if (_points == nil) {
        _points = [[NSMutableArray alloc]init];
    }
    return _points;
}

//懒加载
- (CGContextRef)context{
    if (_context == nil) {
        _context = UIGraphicsGetCurrentContext();
    }
    return _context;
}

//重写初始化方法,并设置笔颜色
- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        //设置默认属性
        self.color = [UIColor blackColor];
        self.lineWidth = 1;
    }
    return self;
}

/*
 如果你的视图只显示背景颜色，或者如果你的视图将其内容直接设置为底层对象，你就不必重写此方法
 
 通过该方法被调用时，UIKit配置绘图环境适当的视图，你可以简单地调用任何绘图方法和功能
 
 此方法每次调用,都会刷新视图,也就是说并不能保存前面绘画的内容
 */
- (void)drawRect:(CGRect)rect{
    if (self.points.count < 2) {
        return;
    }
    
    //设置画笔粗细
    CGContextSetLineWidth(self.context, self.lineWidth);
    //设置画笔颜色
    CGContextSetStrokeColorWithColor(self.context, self.color.CGColor);
    
    //画前面保存的
    for (NSArray *tempPoints in self.allPoints) {
        for (int i = 0; i < tempPoints.count - 1; i++) {
            CGPoint point1 = [tempPoints[i] CGPointValue];
            CGPoint point2 = [tempPoints[i + 1] CGPointValue];
            //线段开始点
            CGContextMoveToPoint(self.context, point1.x, point1.y);
            //线段结束点
            CGContextAddLineToPoint(self.context, point2.x, point2.y);
            //使用当前笔画粗细,颜色来画一条线
            CGContextStrokePath(self.context);
        }
    }
    
    //画最新的
    for (int i = 0; i < self.points.count - 1; i++) {
        CGPoint point1 = [self.points[i] CGPointValue];
        CGPoint point2 = [self.points[i + 1] CGPointValue];
        CGContextMoveToPoint(self.context, point1.x, point1.y);
        CGContextAddLineToPoint(self.context, point2.x, point2.y);
        CGContextStrokePath(self.context);
    }
}

//不支持多点触摸
- (BOOL)isMultipleTouchEnabled{
    return NO;
}

//触摸开始
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.points removeAllObjects];
    //记录初始点
    CGPoint pt = [[touches anyObject] locationInView:self];
    [self.points addObject:[NSValue valueWithCGPoint:pt]];
}

//触摸中
- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //记录当前点
    CGPoint pt = [[touches anyObject] locationInView:self];
    [self.points addObject:[NSValue valueWithCGPoint:pt]];
    //绘图,会调用drawRect方法
    [self setNeedsDisplay];
}

//触摸结束
- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    if (self.points.count < 2) {
        return;
    }
    //将这次的点组合保存到全部点当中
    //注意:此处为什么要另外创建一个数组
    NSArray *tempArr = [[NSArray alloc]initWithArray:self.points];
    [self.allPoints addObject:tempArr];
}

@end
